<template>
  <div id="Login">
    <h3 class="l-title">欢迎使用亲青创</h3>
    <p class="l-tip">验证手机号直接注册或登录</p>
    <section class="c-form">
      <van-cell-group>
        <van-field v-model="formData.phone" placeholder="请输入手机号">
          <div slot="label" class="c-form__cmp">+86</div>
        </van-field>
        <van-field v-model="formData.captcha" placeholder="请输入验证码">
          <button slot="button" @click="counter||sendCode()" class="c-form__valid">
            {{ counter ? `${counter}秒后再试` : '获取验证码' }}
          </button>
        </van-field>
      </van-cell-group>
    </section>
    <van-button @click="onSubmit" :disabled="!formData.captcha" class="l-btn">登录</van-button>
  </div>
</template>
<script lang="ts">
import Vue, {ComponentOptions, VueConstructor} from "vue"
import Component from 'vue-class-component'
import {requestByPost} from "@/utils/request";
import {failToast} from "@/utils/logic";
import {mapActions} from "vuex";
import {Prop} from "vue-property-decorator";

const MAX_COUNTER = 60;
let timer;
@Component({
  methods: mapActions(["login"])
})
export default class Login extends Vue implements ComponentOptions<Vue> {
  name = "Login";
  formData: any = {phone: null, captcha: null}
  counter = 0;
  login!: any;
  @Prop() oldPath!: string;

  async sendCode() {
    const {phone} = this.formData;
    if (!/1\d{10}/.test(phone)) return failToast("请输入合法手机号");
    await requestByPost(`/zqqc/getCaptcha`, {phone});
    this.$toast("操作成功！");
    this.counter = MAX_COUNTER;
    timer = setInterval(() => --this.counter || this.cleanInterval(), 1000);
    this.$once("hook:destroyed", this.cleanInterval)
  }

  cleanInterval() {
    clearInterval(timer)
  }

  async onSubmit() {
    await this.login(this.formData);
    this.$toast.success("登录成功！");
    return this.$replaceRoute(this.oldPath);
  }
}
</script>

<style scoped lang="scss">
@import "~assets/common.scss";

#Login {
  height: 100vh;
  text-align: center;
  padding: 28px 28px 0 28px;
  box-sizing: border-box;
  background: #fff;

  .l-title {
    font-size: 24px;
    color: #333;
  }

  .l-tip {
    font-size: 12px;
    margin-top: 16px;
    color: $p-color;
  }

  .c-form {
    margin-top: 24px;

    /deep/ .van-field__label {
      width: auto;
    }

    /deep/ .c-form__cmp {
      border-right: 1PX solid $border-clr;
      padding-right: 10px;
    }

    /deep/ .c-form__valid {
      border: 0;
      outline: 0;
      background: none;
      color: #349e7e;
      font-size: 16px;
    }
  }

  .l-btn {
    width: 100%;
    color: white;
    margin-top: 22px;
    background-color: #349e7e;
    border: 1px solid #349e7e;
  }
}
</style>
